'use strict';

const Controller = require('egg').Controller;

// const helmet = require('helmet');
// const redis = require("redis");
// const client = redis.createClient();
// client.on("error", function(error) {
//   console.error(error);
// });
class MainController extends Controller {
  async index() {
    // 首页的文章列表数据
    console.log(this.ctx);

    this.ctx.body = 'hi api';
  }
  async updateTopicItem() {
    const tmpArticle = this.ctx.request.body;
    const result = await this.app.mysql.update('topicList', tmpArticle);
    const updateSuccess = result.affectedRows === 1;
    console.log(updateSuccess);
    this.ctx.body = {
      isScuccess: updateSuccess,
    };
  }
  // 修改文章
  async updateArticle() {
    const tmpArticle = this.ctx.request.body;
    const result = await this.app.mysql.update('article', tmpArticle);
    const updateSuccess = result.affectedRows === 1;
    console.log(updateSuccess);
    this.ctx.body = {
      isScuccess: updateSuccess,
    };
  }
  // 获得文章列表
  async getArticleList() {
    // let sql =
    //   "SELECT article.id as id," +
    //   "article.title as title," +
    //   "article.introduce as introduce," +
    //   "article.addTime as addTime," +
    //   "article.articleImg as articleImg," +
    //   // "FROM_UNIXTIME(article.addTime,'%Y-%m-%d' ) as addTime," +
    //   'article.article_count as part_count ,'+
    //   'article.view_count as view_count ,'+
    //   "type.typeName as typeName " +
    //   "FROM article LEFT JOIN type ON article.type_id = type.Id " +
    //   "ORDER BY article.id DESC ";

    const sql = 'SELECT * FROM article';

    const resList = await this.app.mysql.query(sql);
    this.ctx.body = { list: resList };
  }
  // 后台文章分类信息
  async getTypeInfo() {
    // const resType = await this.app.mysql.select("type");
    const sql = 'SELECT * FROM type';
    const result = await this.app.mysql.query(sql);
    this.ctx.body = { data: result };
  }
  // 添加文章
  async addArticle() {
    const tmpArticle = this.ctx.request.body;

    // 查询文章是否已存在  标示--- title + type_id
    const searchArticle = await this.app.mysql.select('article', {
      where: {
        title: tmpArticle.title,
        type_id: tmpArticle.type_id,
      },
    });
    // console.log(tmpArticle,'====================================');
    // console.log(searchArticle)
    if (searchArticle.length > 0) {
      this.ctx.body = {
        isError: '文章名已存在',
      };
    } else {
      const result = await this.app.mysql.insert('article', tmpArticle);
      const insertSuccess = result.affectedRows === 1;
      const insertId = result.insertId;

      this.ctx.body = {
        isScuccess: insertSuccess,
        insertId,
      };
    }
  }
  async getShareTopic() {
    let sql,
      sqlAll;

    const endTime = +this.ctx.query.endTime > 0 ? this.ctx.query.endTime : new Date().getTime();
    const startTime = +this.ctx.query.startTime > 0 ? this.ctx.query.startTime : new Date('1997-01-01').getTime();
    if (this.ctx.query.searchTxt) {
      sql = `SELECT * FROM shareTopic where shareTopicTitle like '%${this.ctx.query.searchTxt}%' and updateTime between '${startTime}' and '${endTime}' Order By updateTime Desc limit ${(this.ctx.query.pageIndex - 1) * this.ctx.query.pageSize},${this.ctx.query.pageSize}`;
      sqlAll = `select count(*) as count from shareTopic where shareTopicTitle like '%${this.ctx.query.searchTxt}%' and updateTime between '${startTime}' and '${endTime}'`;
    } else {
      if (this.ctx.query.pageIndex) {
        sql = `SELECT * FROM shareTopic where updateTime between '${startTime}' and '${endTime}' Order By updateTime Desc limit ${(this.ctx.query.pageIndex - 1) * this.ctx.query.pageSize},${this.ctx.query.pageSize}`;
        sqlAll = `SELECT count(*) as count FROM shareTopic where updateTime between '${startTime}' and '${endTime}'`;
      } else {
        sql = `SELECT * FROM shareTopic where updateTime between '${startTime}' and '${endTime}' Order By updateTime Desc`;
        sqlAll = `select count(*) as count from shareTopic where updateTime between '${startTime}' and '${endTime}'`;
      }

    }
    // sql = `SELECT * FROM shareTopic`
    // let sql = 'SELECT * FROM shareTopic'
    const resultList = await this.app.mysql.query(sql);
    const resulttotal = await this.app.mysql.query(sqlAll);
    this.ctx.set('x-frame-options', false);
    this.ctx.set('Access-Control-Expose-Headers', 'Content-Disposition,Date');
    this.ctx.body = { list: resultList, total: resulttotal[0].count };
  }
  async getTopicListById() {
    const id = this.ctx.params.id;
    const sql = `SELECT * FROM shareTopic WHERE id=${id}`;
    const result = await this.app.mysql.query(sql);
    this.ctx.body = { data: result };
  }
  async getTopicById() {
    const id = this.ctx.params.id;
    const sql = `SELECT * FROM topicList WHERE id=${id}`;
    const result = await this.app.mysql.query(sql);
    this.ctx.body = { data: result };
  }
  async updateShareTopic() {
    const data = this.ctx.request.body;
    const res = await this.app.mysql.update('shareTopic', data);
    const updateSuccess = res.affectedRows === 1;
    this.ctx.body = {
      isScuccess: updateSuccess,
    };
  }
  // async addTopicItems() {
  //   // let reqBody = this.ctx
  //   console.log("6666666666666") topicList

  // }
  async addTopicItems() {
    // 首页的文章列表数据
    const ctxBody = this.ctx.request.body;
    const searchTopic = await this.app.mysql.select('topicList', {
      where: {
        title: ctxBody.title,
      },
    });
    if (searchTopic.length > 0) {
      this.ctx.body = {
        isError: '数据名已存在',
      };
    } else {
      const result = await this.app.mysql.insert('topicList', ctxBody);
      const insertSuccess = result.affectedRows === 1;

      const insertId = result.insertId;

      this.ctx.body = {
        isScuccess: insertSuccess,
        insertId,
      };
    }
  }
  // 添加专题  addShareTopic client
  async addShareTopic() {

    const addShareTopic = this.ctx.request.body;
    const searchLength = await this.app.mysql.select('shareTopic', {
      where: {
        shareTopicTitle: addShareTopic.shareTopicTitle,
      },
    });
    if (searchLength.length > 0) {
      this.ctx.body = {
        isError: '数据名已存在',
      };
    } else {
      // client.set('shareTopic', addShareTopic, function (err, response) {
      //   if (err) {
      //     console.log("err:", err);
      //   } else {
      //     console.log(response);
      //     client.get('key001', function (err, res) {
      //       if (err) {
      //         console.log("err:", err);
      //       } else {
      //         console.log(res,"88888888");
      //         client.end();
      //       }
      //     });
      //   }
      // })
      const result = await this.app.mysql.insert('shareTopic', addShareTopic);
      const insertSuccess = result.affectedRows === 1;

      const insertId = result.insertId;

      this.ctx.body = {
        isScuccess: insertSuccess,
        insertId,
      };
    }

  }

  async getTopicList() {

    const endTime = +this.ctx.query.endTime > 0 ? this.ctx.query.endTime : new Date().getTime();
    const startTime = +this.ctx.query.startTime > 0 ? this.ctx.query.startTime : new Date('1997-01-01').getTime();
    const searchTxt = this.ctx.query.searchTxt ? this.ctx.query.searchTxt : '';
    let sql,
      sqlAll;
    //  { pageSize: 5, pageIndex: 1 }    and title like '${searchTxt}' searchType
    if (searchTxt) {
      if (this.ctx.query.searchID) {
        sql = `SELECT * FROM topicList where cast(topic_id as char) like '${this.ctx.query.searchID}' and title like '%${searchTxt}%' and addTime between '${startTime}' and '${endTime}' Order By updateTime Desc  limit ${(this.ctx.request.query.pageIndex - 1) * this.ctx.request.query.pageSize},${this.ctx.request.query.pageSize} `;
      } else {
        sql = `SELECT * FROM topicList where addTime between '${startTime}' and '${endTime}' and title like '%${searchTxt}%' Order By updateTime Desc limit ${(this.ctx.request.query.pageIndex - 1) * this.ctx.request.query.pageSize},${this.ctx.request.query.pageSize} `;
      }
    } else {
      if (this.ctx.query.searchID) {
        sql = `SELECT * FROM topicList where cast(topic_id as char) like '${this.ctx.query.searchID}' and addTime between '${startTime}' and '${endTime}' Order By updateTime Desc limit ${(this.ctx.request.query.pageIndex - 1) * this.ctx.request.query.pageSize},${this.ctx.request.query.pageSize} `;
      } else {
        sql = `SELECT * FROM topicList where addTime between '${startTime}' and '${endTime}' Order By updateTime Desc limit ${(this.ctx.request.query.pageIndex - 1) * this.ctx.request.query.pageSize},${this.ctx.request.query.pageSize}`;
      }

    }

    if (searchTxt) {
      if (this.ctx.query.searchID) {
        sqlAll = `SELECT * FROM topicList where cast(topic_id as char) like '${this.ctx.query.searchID}' and title like '%${searchTxt}%' and addTime between '${startTime}' and '${endTime}'`;
      } else {
        sqlAll = `SELECT * FROM topicList where addTime between '${startTime}' and '${endTime}' and title like '%${searchTxt}%' `;
      }
    } else {
      if (this.ctx.query.searchID) {
        sqlAll = `SELECT * FROM topicList where cast(topic_id as char) like '${this.ctx.query.searchID}' and addTime between '${startTime}' and '${endTime}' `;
      } else {
        sqlAll = `SELECT * FROM topicList where addTime between '${startTime}' and '${endTime}'`;
      }

    }
    // console.log('9999999+', sql);
    // console.log(this.app.redis,"++++++++++++++++++++++");

    const res = await this.app.mysql.query(sql);
    // let sqlAll = `SELECT * FROM topicList`
    const resAll = await this.app.mysql.query(sqlAll);

    this.ctx.body = {
      data: {
        list: res,
        total: resAll.length,
      },
    };
  }

  async delTopicList() {
    const id = this.ctx.params.id;
    const res = await this.app.mysql.delete('topicList', { id });
    this.ctx.body = { data: res };
  }
  async delTopic() {
    const id = this.ctx.params.id;
    const res = await this.app.mysql.delete('shareTopic', { id });
    this.ctx.body = { data: res };
  }
  // 添加密圈
  async addMiQuan() {
    const tmpMiQuan = this.ctx.request.body;
    // console.log(tmpMiQuan,"999999----addMiQuan");
    const searchLength = await this.app.mysql.select('miquan', {
      where: {
        miQuanAuthor: tmpMiQuan.miQuanAuthor,
      },
    });
    if (searchLength.length > 0) {
      this.ctx.body = {
        isError: '数据名已存在',
      };
    } else {
      const result = await this.app.mysql.insert('miquan', tmpMiQuan);
      const insertSuccess = result.affectedRows === 1;

      const insertId = result.insertId;

      this.ctx.body = {
        isScuccess: insertSuccess,
        insertId,
        tmpMiQuan,
      };
    }
  }
  // 修改文章
  async updateMiQuan() {
    const tmpArticle = this.ctx.request.body;
    console.log('111111', tmpArticle);

    const result = await this.app.mysql.update('miquan', tmpArticle);
    const updateSuccess = result.affectedRows === 1;
    this.ctx.body = {
      isScuccess: updateSuccess,
    };
  }
  // 获得密圈列表
  async getMiQuanList() {
    const sql =
      'SELECT * from miquan';

    const resList = await this.app.mysql.query(sql);
    this.ctx.body = { list: resList };
  }
  // 删除文章
  async delMiquan() {
    const id = this.ctx.params.id;
    const res = await this.app.mysql.delete('miquan', { id });
    this.ctx.body = { data: res };
  }
  // 添加类别
  async addType() {
    const tmpArticle = this.ctx.request.body;
    // tmpArticle.
    const result = await this.app.mysql.insert('article', tmpArticle);
    const insertSuccess = result.affectedRows === 1;
    const insertId = result.insertId;

    this.ctx.body = {
      isScuccess: insertSuccess,
      insertId,
    };
  }

  // 根据密圈ID得到密圈详情，用于修改密圈
  async getMiQuanById() {
    const id = this.ctx.params.id;
    const sql = `SELECT * FROM miquan WHERE id=${id}`;
    const result = await this.app.mysql.query(sql);
    this.ctx.body = { data: result };
  }

  // 根据文章ID得到文章详情，用于修改文章
  async getArticleById() {
    const id = this.ctx.params.id;
    const sql = `SELECT * FROM article WHERE article.id = ${id}`;
    const result = await this.app.mysql.query(sql);
    this.ctx.body = { data: result };
  }
  // 删除文章
  async delArticle() {
    const id = this.ctx.params.id;
    const res = await this.app.mysql.delete('article', { id });
    this.ctx.body = { data: res };
  }
  // 判断用户名密码是否正确
  async checkLogin() {
    const userName = this.ctx.request.body.userName;
    const password = this.ctx.request.body.password;
    const sql =
      " SELECT userName FROM admin_user WHERE userName = '" +
      userName +
      "' AND password = '" +
      password +
      "'";

    const res = await this.app.mysql.query(sql);

    if (res.length > 0) {
      // 登录成功,进行session缓存
      const openId = new Date().getTime();
      this.ctx.session.openId = { openId };
      this.ctx.body = { data: '登录成功', openId };
    } else {
      this.ctx.body = { data: '登录失败' };
    }
  }


  // 题库数据接口
  async getTaskType() {
    const sql = 'SELECT * FROM taskType';
    const result = await this.app.mysql.query(sql);
    const insertSuccess = result.affectedRows === 1;
    this.ctx.body = {
      data: result,
      status: insertSuccess,
    };
  }
  async delTaskType() {
    const id = this.ctx.params.id;
    const res = await this.app.mysql.delete('taskType', { taskType_id: id });
    this.ctx.body = { data: res };
  }
  async addTaskType() {
    let results;
    const addBody = this.ctx.request.body;
    if (addBody.taskType_id) {
      results = await this.app.mysql.update('taskType', addBody, { where: { taskType_id: `${addBody.taskType_id}` } });
    } else {
      results = await this.app.mysql.insert('taskType', addBody);
    }
    const insertSuccess = results.affectedRows === 1;
    this.ctx.body = {
      data: results,
      status: insertSuccess,
    };
    // let sql ="SELECT * FROM taskType"
    // const result = await this.app.mysql.query(sql)
    // const insertSuccess = result.affectedRows === 1;
    // this.ctx.body = {
    //   data: result,
    //   status: insertSuccess
    // }

  }
  async getTaskList() {
    const sql = 'SELECT * FROM taskStore';
    const result = await this.app.mysql.query(sql);
    this.ctx.body = { data: result, status: true };
  }

  async getTaskListById() {
    const id = this.ctx.params.id;
    const sql = `SELECT * FROM taskList where taskType_id = ${id}`;
    const result = await this.app.mysql.query(sql);
    this.ctx.body = { data: result, status: true };
  }
  // Update taskList Set taskType ='前端' Where taskList_id=1;
  async addTaskStore() {
    const tmpArticle = this.ctx.request.body;
    // console.log('22222',tmpArticle);

    // tmpArticle.
    const result = await this.app.mysql.insert('taskStore', tmpArticle);
    const insertSuccess = result.affectedRows === 1;
    const insertId = result.insertId;

    this.ctx.body = {
      isScuccess: insertSuccess,
      insertId,
    };
  }
  async updateTaskList() {
    const id = this.ctx.params.id;
    let result;
    console.log('33333...', this.ctx.request.body);
    if (this.ctx.request.body.length) {
      result = await this.app.mysql.update('taskList', { taskList_info: (JSON.stringify(this.ctx.request.body)) }, { where: { taskType_id: `${id}` } });
    } else {
      result = await this.app.mysql.delete('taskList', {
        taskType_id: id,
      });
    }

    const updateSuccess = result.affectedRows === 1;
    this.ctx.body = {
      isScuccess: updateSuccess,
    };
  }
  async addTasklIstanbu() {
    const tmpArticle = this.ctx.request.body;
    // console.log('22222',tmpArticle);

    // tmpArticle.
    const result = await this.app.mysql.insert('taskList', tmpArticle);
    const insertSuccess = result.affectedRows === 1;
    const insertId = result.insertId;

    this.ctx.body = {
      isScuccess: insertSuccess,
      insertId,
    };
  }
  async delTaskStore() {
    const id = this.ctx.params.id;
    const res = await this.app.mysql.delete('taskStore', { taskId: id });
    this.ctx.body = { data: res };
  }
}


module.exports = MainController;
